# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>

# include kernel/user

LIBINCLUDE	+= include/

LIBCFLAGS   := -fno-builtin -nostdinc -m32 -Iarch/$(ARCH)/include -Iarch/$(ARCH)/drivers -Darch_$(ARCH)
LIBCFLAGS	+= $(addprefix -I,$(LIBINCLUDE))

LIBDIR	+= lib_common

$(call add_files_cc,$(call listf_cc,$(LIBDIR)),libs, $(LIBCFLAGS))

# -------------------------------------------------------------------

# common part of the kernel

INCLUDEDIR  := include/fs         \
			   include/fs/devs    \
			   include/fs/pipe    \
			   include/fs/sfs     \
			   include/fs/swap    \
			   include/fs/vfs     \
	  		   include/mm         \
			   include/process    \
			   include/schedule   \
			   include/sync

SRCDIR		+= lib 			 \
			   kernel        \
			   mm 			 \
			   fs            \
			   fs/devs       \
			   fs/pipe       \
			   fs/sfs        \
			   fs/swap       \
			   fs/vfs        \

KCFLAGS     := $(foreach dir,$(INCLUDEDIR),$(addprefix -I,$(dir)))

$(call add_files_cc,$(call listf_cc,$(SRCDIR)),kernel,$(KCFLAGS) -fno-builtin -Iarch/$(ARCH)/include -Iarch/$(ARCH)/drivers -Darch_$(ARCH))

OBJS	= $(call read_packet,kernel libs)

# -------------------------------------------------------------------
# user programs

UINCLUDE	:= user/include/ \
			   user/libs/

USRCDIR		+= user

ULIBDIR		+= user/libs

UCFLAGS		:= $(addprefix -I,$(UINCLUDE))
UCFLAGS		+= -fno-builtin -m32 -gstabs -nostdinc -ggdb
USER_BINS	:=

$(call add_files_cc,$(call listf_cc,$(ULIBDIR)),ulibs,$(UCFLAGS))
$(call add_files_cc,$(call listf_cc,$(USRCDIR)),uprog,$(UCFLAGS))

UOBJS	:= $(call read_packet,ulibs libs)

define uprog_ld
__user_bin__ := $$(call ubinfile,$(1))
USER_BINS += $$(__user_bin__)
$$(__user_bin__): tools/user.ld
$$(__user_bin__): $$(UOBJS)
$$(__user_bin__): $(1) | $$$$(dir $$$$@)
	$(V)$(LD) $(LDFLAGS) -T tools/user.ld -o $$@ $$(UOBJS) $(1)
endef

$(foreach p,$(call read_packet,uprog),$(eval $(call uprog_ld,$(p))))

# -------------------------------------------------------------------

# create 'mksfs' tools
$(call add_files_host,tools/mksfs.c,mksfs,mksfs)
$(call create_target_host,mksfs,mksfs)

# -------------------------------------------------------------------

# create fs.img
FSIMG		:= $(call totarget,fs.img)
FSBINS		:=
SFSROOT		:= disk0

define fscopy
__fs_bin__ := $(2)$(SLASH)$(patsubst $(USER_PREFIX)%,%,$(basename $(notdir $(1))))
FSBINS += $$(__fs_bin__)
$$(__fs_bin__): $(1) | $$$$(dir $@)
	@$(COPY) $$< $$@
endef

$(foreach p,$(USER_BINS),$(eval $(call fscopy,$(p),$(SFSROOT)$(SLASH)bin)))

$(FSIMG): $(SFSROOT) $(FSBINS) | $(call totarget,mksfs)
	$(V)dd if=/dev/zero of=$@ bs=1M count=128
	@$(call totarget,mksfs) $@ $(SFSROOT)

$(call create_target,fs.img)

# >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>